package com.lkd.handler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@Component
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)
public class SupplyHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;

    /**
     * 售货机补货
     * @param jsonMsg
     * @throws IOException
     */
    @Override
    public void process(String jsonMsg) throws IOException {
        if (StringUtils.isBlank(jsonMsg)) {
            return;
        }
        //解析消息
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        Optional.ofNullable(supplyContract).ifPresent(supply -> {
                    List<SupplyChannel> supplyData = supply.getSupplyData();
                    List<TaskDetailsViewModel> details = new ArrayList<>(supplyData.size());
                    if (CollectionUtils.isEmpty(supplyData)) {
                        return;
                    }
                    //循环装换货道信息
                    for (SupplyChannel supplyChannel : supplyData) {
                        TaskDetailsViewModel model = new TaskDetailsViewModel();
                        BeanUtils.copyProperties(supplyChannel,model);
                        model.setChannelCode(supplyChannel.getChannelId());
                        model.setExpectCapacity(supplyChannel.getCapacity());
                        details.add(model);
                    }

                    taskService.AutoDistributeTask(supply.getInnerCode(), VMSystem.TASK_TYPE_SUPPLY, details);
                }
        );
    }
}
















